<template>
  <div class="card">
    <div class="card-body">
      <h5 class="card-title">任务列表</h5>
      <div class="mb-3">
        <button class="btn btn-danger" :disabled="selectedTasks.length === 0" @click="batchDelete">
          批量删除
        </button>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleSelectAll" /></th>
            <th>标题</th>
            <th>描述</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <TaskItem
            v-for="task in tasks"
            :key="task.id"
            :task="task"
            :selected="selectedTasks.includes(task.id)"
            @toggle-selection="toggleSelection"
            @task-updated="$emit('task-updated')"
            @task-deleted="$emit('task-deleted')"
            @edit-task="$emit('edit-task', $event)"
          />
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import TaskItem from './TaskItem.vue';
import { batchDeleteTasks } from '../api';

export default {
  name: 'TaskList',
  components: { TaskItem },
  props: {
    tasks: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      selectedTasks: [],
      selectAll: false,
    };
  },
  methods: {
    toggleSelection(taskId) {
      if (this.selectedTasks.includes(taskId)) {
        this.selectedTasks = this.selectedTasks.filter((id) => id !== taskId);
      } else {
        this.selectedTasks.push(taskId);
      }
    },
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedTasks = this.tasks.map((task) => task.id);
      } else {
        this.selectedTasks = [];
      }
    },
    async batchDelete() {
      if (confirm('确定要删除选中的任务吗？')) {
        try {
          await batchDeleteTasks(this.selectedTasks);
          this.$emit('task-deleted');
          this.selectedTasks = [];
          this.selectAll = false;
        } catch (error) {
          console.error('批量删除失败:', error);
        }
      }
    },
  },
};
</script>